#include "lcd.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <linux/fb.h>
#include <unistd.h>
lcd *lcd_init(void)
{
    lcd *s = malloc(sizeof(*s));
    s->fd_lcd = open("/dev/fb0", O_RDWR);
    if (s->fd_lcd == -1)
    {
        perror("lcd error");
        return NULL;
    }

    struct fb_var_screeninfo fbinfo;
    int red = ioctl(s->fd_lcd, FBIOGET_VSCREENINFO, &fbinfo);
    if (red == -1)
    {
        perror("ioctl error");
        return NULL;
    }
    s->w_lcd = fbinfo.xres;
    s->h_lcd = fbinfo.yres;
    s->size_lcd = fbinfo.bits_per_pixel / 8;
    printf("w=%d h=%d size=%d\n", s->w_lcd, s->h_lcd, s->size_lcd);

    s->plcd = (int *)mmap(NULL, s->w_lcd * s->h_lcd * s->size_lcd, PROT_READ | PROT_WRITE, MAP_SHARED, s->fd_lcd, 0);
    if (s->plcd == MAP_FAILED)
    {
        perror("mmap error");

        return NULL;
    }

    return s;
}

void lcd_close(lcd *s)
{
    close(s->fd_lcd);
    munmap(s->plcd, s->w_lcd * s->h_lcd * s->size_lcd);
}

void hua_dian(lcd *s, int x, int y, int color)
{
    if (x >= 0 && x < s->w_lcd && y >= 0 && y < s->h_lcd)
    {
        *(s->plcd + y * s->w_lcd + x) = color;
    }
}